import { createRouter, createWebHistory } from 'vue-router'
import { concat } from 'lodash-es'
import global from './global.js'
import normal from './normal.js'
import management from './management.js'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import Config from '@/config'
import message from 'ant-design-vue/lib/message/index.js'
NProgress.configure({ showSpinner: false })

export const normalRouter = createRouter({
  history: createWebHistory(),
  routes: concat(global, normal)
})

export const managementRouter = createRouter({
  history: createWebHistory(),
  routes: concat(global, management)
})

export const globalRouter = createRouter({
  history: createWebHistory(),
  routes: global
})

configRouter(normalRouter)
configRouter(managementRouter)
configRouter(globalRouter)

function configRouter(router) {
  router.beforeEach(async to => {
    NProgress.start()
    if (store.state.user.token) {
      // 针对管理视图检查权限路由权限
      if (to.meta.roles && typeof to.meta.roles.split === 'function') {
        const roles = to.meta.roles.split(',')
        if (!roles.some(role => store.getters['user/' + role.trim()] === true)) {
          return '/404'
        }
      }
      // 针对客户详情页检查路由权限
      if (to.path.match(/^\/client\//i)) {
        await store.dispatch('client/getPermissions', to.params.id)
        const permissions = store.state.client.permissions
        // 访问客户首页则查找第一个有权限的页面
        if (to.name === 'Client Detail') {
          for (const children of to.matched[0].children) {
            if (permissions.find(permission => permission.auth === children.meta.permission)) {
              return router.resolve({ name: children.name, params: { id: to.params.id } })
            }
          }
          return '/404'
        }
        if (!permissions.find(permission => permission.auth === to.meta.permission)) {
          return '/404'
        }
      }
      document.title = to.meta && to.meta.title ? to.meta.title : to.name
    } else {
      try {
        await store.dispatch('user/login')
        document.title = to.meta && to.meta.title ? to.meta.title : to.name
      } catch (e) {
        NProgress.done()
        message.error('Authentication failed, Please re-login.')
        setTimeout(() => {
          window.location = Config.LOGIN_URL + Config.APP_HOST + to.fullPath
        }, 5000)
        return false
      }
    }
  })
  router.afterEach(() => {
    NProgress.done()
  })
}
